import { sanitizeHtml, sanitizeText } from '../utils/xss'

/**
 * XSS防护指令
 * 用于自动清理绑定的内容
 */

// v-xss-safe 指令 - 清理HTML内容
export const xssSafe = {
  mounted(el: HTMLElement, binding: any) {
    const content = binding.value
    if (content) {
      el.innerHTML = sanitizeHtml(content)
    }
  },
  updated(el: HTMLElement, binding: any) {
    const content = binding.value
    if (content) {
      el.innerHTML = sanitizeHtml(content)
    }
  }
}

// v-xss-text 指令 - 清理纯文本内容
export const xssText = {
  mounted(el: HTMLElement, binding: any) {
    const content = binding.value
    if (content) {
      el.textContent = sanitizeText(content)
    }
  },
  updated(el: HTMLElement, binding: any) {
    const content = binding.value
    if (content) {
      el.textContent = sanitizeText(content)
    }
  }
}

// 注册所有指令
export function registerXssDirectives(app: any) {
  app.directive('xss-safe', xssSafe)
  app.directive('xss-text', xssText)
}

export default {
  xssSafe,
  xssText,
  registerXssDirectives
}